<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="title-bar">
            <img class="logo" src="../assets/logo.svg" alt="logo" />
            <div class="title">jihui  云图库</div>
          </div>
        </RouterLink>
      </a-col>
      <a-col flex="auto">
        <a-menu v-model:selectedKeys="current" mode="horizontal" :items="items" @click="doMenuClick" />
      </a-col>
      <a-col flex="120px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser?.id">
            <a-dropdown>
              <ASpace>
                <a-avatar :src="loginUserStore.loginUser.userAvatar">
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
                {{ loginUserStore.loginUser.userName ?? '无名' }}
              </ASpace>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>

          </div>
          <div v-else>
            <a-space>
              <a-button type="primary" href="/user/login">登录</a-button>
              <a-button type="primary" href="/user/register">注册</a-button>
            </a-space>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { computed, h, ref } from 'vue'
import { HomeOutlined, UserOutlined, LogoutOutlined } from '@ant-design/icons-vue'
import { MenuProps, message } from 'ant-design-vue'
import { useRouter } from "vue-router";
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { userLogoutUsingPost } from '@/apis/UserInterface.ts'

const loginUserStore = useLoginUserStore()

// 菜单列表
const originItems = [
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页',
  },
  {
    key: '/admin/userManager',
    label: '用户管理',
    title: '用户管理',
    meta: {
      auth: true,
      role: ['admin'],
    }
  },
  {
    key: '/edit_picture',
    label: '创建图片',
    title: '创建图片',
    meta: {
      auth: true,
    }
  },
  {
    key: '/admin/pictureManager',
    label: '图片管理',
    title: '图片管理',
    meta: {
      auth: true,
      role: ['admin'],
    }
  },
  {
    key: '/admin/spaceManager',
    label: '空间管理',
    title: '空间管理',
    meta: {
      auth: true,
      role: ['admin'],
    }
  },
  {
    key: 'others',
    label: h('a', { href: 'https://gitee.com/jihui-31', target: '_blank' }, '关于作者'),
    title: '关于作者',
  },
]
// 过滤菜单项
const filterMenus = (menus: MenuProps['items'] = []) => {
  return menus.filter((menu) => {
    const loginUser = loginUserStore.loginUser; // 确保正确获取用户
    // 未登录
    const isNotLoggedIn = !loginUser;
    if (menu?.meta) {
      const { auth, role } = menu.meta;

      if (auth || role) { // 需要认证或有角色限制
        if (isNotLoggedIn) return false; // 未登录直接拦截
      }

      if (role && !role.includes(loginUser?.userRole)) {
        return false; // 角色不符合
      }
    }
    return true;
  });
};
// 展示在菜单的路由数组
const items = computed<MenuProps['items']>(() => filterMenus(originItems))

const router = useRouter();
// 路由跳转事件
const doMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  });
};

// 用户注销
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  console.log(res)
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    //await router.push('/user/login')
    window.location.href = `/user/login`
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}

// 当前选中菜单
const current = ref<string[]>([]);
// 监听路由变化，更新当前选中菜单
router.afterEach((to, from, next) => {
  current.value = [to.path];
});
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
  padding-bottom: 10px;
}
</style>
